package com.gcb.socket;

/**
 * Created by IntelliJ IDEA.
 * User: chendt
 * Date: 2008-7-30
 * Time: 9:33:06
 * To change this template use File | Settings | File Templates.
 */
import java.io.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import javax.swing.*;
import java.io.FileOutputStream;
import java.net.*;

public class Serve extends Applet implements ActionListener{
  private Frame f;
  File file;
  private TextArea ta;
  public FileOutputStream dout=null;
  public FileInputStream  din =null;
  byte[] buf = new byte[1024];
  StringBuffer sb=new StringBuffer();
  private Button exit;
  private TextArea userlist;  //显示用户列表
  private Button refresh;     //用于更新显示连接情况
  int threadnum=0;

  ServerThread[] threadbuf=new ServerThread[100];//最大连接数为100

  public static void main(String args[])
  {
    Serve myform=new Serve();
    myform.go();
  }
  public void go()
  {

    f=new Frame("服务器端");
    exit=new Button("退出");
    userlist=new TextArea(10,60);
    refresh=new Button("更新");
    f.setLayout(new FlowLayout());
    ta=new TextArea(15,70);
    ta.setEditable(false);
    f.add(ta);
    f.add(userlist);
    f.add(refresh);
    f.add(exit);
    f.setSize(550,400);
    f.setVisible(true);
    file=new File(".","Receive.txt");
    ta.setText(readfile());
    exit.addActionListener(this);
    refresh.addActionListener(this);
    try{
      ServerSocket server=new ServerSocket(2000);
      int i=1;
      for(;;)
      {
        Socket incoming=server.accept();
        threadbuf[i]=new ServerThread(incoming,i,this);
        threadbuf[i].start();
        threadnum++;
        i++;  
      }
    } catch(IOException ex) {ex.printStackTrace();};

  }
  public String readfile()
  {
      ///////////////////////////////////////////////
      try
      {
          din=new FileInputStream(file);
          while((din.read(buf))!=-1)
          {
              sb.append(new String(buf));
              buf=new byte[1024];//重新生成，避免和上次读取的数据重复
          }
      }catch(IOException ioe){}
      ///////////////////////////////////////////////
      return sb.toString();
  }
  public void actionPerformed(ActionEvent e)
  {
    if(e.getSource()==exit)
    {
      System.exit(0);
    }
    if(e.getSource()==refresh)
    {
      showuser();
    }
  }
  public void AddMessage(String str)
  {
    ta.append(str+"\n");
  }
  public void showuser()
  {
    String usermessage;
    userlist.setText("");
    for(int i=1;i<=threadnum;i++)
    {
      if(threadbuf[i].isAlive())
      {
         usermessage="用户名:"+threadbuf[i].getName()+" 连接时间:"+threadbuf[i].starttime+" 持续时间:"+threadbuf[i].getlasttime()+" 用户IP:"+threadbuf[i].getIP()+"\n";
         userlist.append(usermessage);
      }
    }
  }
  
}
